import { computed, ref } from 'vue';
import store from '@/store'
import { PollTask } from '@/lib/tools'

export default function useReport() {
   /** --------------心跳 start -------------- */


   const report = ref();

    // 全部备案信息
    const publishBrand = computed(() => {
        return store.state.brand?.publishBrand || {};
    })

    // 获取当前用户信息
    const currentUser = computed(() => {
        return store.state?.currentUser || {};
    })

    // 观看时间
    let watchInterval = null;
    const watchTime = ref(0);


    let poll = null;

    // 发心跳异常次数
    const reportFnTime = ref(0);

    // 发送心跳间隔时间
    const reportIntervalTime = ref(0);

    // 根据心跳配置发送心跳数据
    function reportFn(moocId, courseWareId, watchLocation = 0) {
        report.value = {moocId, courseWareId, watchLocation};
        reportFnTime.value ++;
        G_transmit('hbPolicy', {}).then(async(res) => {
            reportIntervalTime.value = res.data.interval;
            if(reportIntervalTime.value) {
                try {
                    poll = new PollTask();
                    await poll.startPoll(hbReport, validateCode, reportIntervalTime.value * 1000);
                }catch (error) {
                    reportErrorEvent();
                }
            }
        }).catch((_err) => {
            reportErrorEvent();
            console.log(_err)
        })
    }

    // 结束心跳
    function endReportFn() {
        poll && poll.abortPoll();
    }

    /**
     * policy 请求失败
     * a) 尝试3次请求policy（每次间隔 5 秒），<=3 次以内成功，正常发心跳
     * b) 尝试3次请求policy（每次间隔 5 秒），>3 不在尝请求使用默认心跳间隔发送心跳（默认间隔为25），正常发心跳
     */
    async function reportErrorEvent() {
        if(reportFnTime.value < 3) {
            setTimeout(() => {
                reportFn();
            }, 5000);   
        } else {
            reportIntervalTime.value = 25 * 1000;
            if(!poll) {
                poll = new PollTask();
            }
            await poll.startPoll(hbReport, validateCode, reportIntervalTime.value);
        }
    }

    function validateCode(result) {
        return false;
    }

    // 上报心跳
    async function hbReport(watchLocation = 0) {
        if(watchTime.value === 0) {
             return;
        }
        let params = {
            appId: 100002,
            bizId: report.value.moocId,
            bizType: 'mooc',
            dataType: 'pull2',
            device: window.navigator.userAgent,
            resId: report.value.courseWareId,
            resSource: 'courseWare',
            resType: 'rec',
            userClient: 'PC-DEFAULT',
            watchTime: watchTime.value,
            dtBrand: publishBrand.value.brand,
            dtTenant: publishBrand.value.brandTenant.tenant,
            packageName: 'ruiyun2-mooc-web',
            bizUserId: currentUser.value.userId,
            realName: currentUser.value.name,
            headImage: currentUser.value.icon
        }
        let watchLocation1 = watchLocation || report.value.watchLocation;
        if(watchLocation1>= 0) { // 观看位置
            params.watchLocation = watchLocation1;
        }

        let res = await G_transmit('hbReport', {
            data: params,
        })
        watchTime.value = 0;
        return res;
    }

    // 开始计算看课时间
    function startWatchTime() {
        if(watchInterval) {
            endWatchTime();
        }
        watchInterval = setInterval(() => {
            watchTime.value++;
        }, 1000);
    }

    // 开始计算看课时间
    function endWatchTime() {
        if (watchInterval) {
            clearInterval(watchInterval);
            watchInterval = null;
        }
    }

    return{
        reportFn, startWatchTime, endWatchTime, endReportFn, hbReport
    }
}
